package logger

import (
	"io"
	"os"
	"sync"
	"time"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"gopkg.in/natefinch/lumberjack.v2"
)

var once sync.Once

func initLogger() {
	consoleWriter := zerolog.ConsoleWriter{
		Out:        os.Stderr,
		TimeFormat: time.RFC3339,
		NoColor:    false,
	}

	fileWriter := lumberjack.Logger{
		Filename:   "logs/app.log",
		MaxSize:    10, // megabytes
		MaxBackups: 5,
		MaxAge:     30, // days
		Compress:   true,
	}

	zerolog.SetGlobalLevel(zerolog.InfoLevel)
	zerolog.TimeFieldFormat = time.RFC3339

	multiWriter := zerolog.MultiLevelWriter(
		consoleWriter,
		io.MultiWriter(&fileWriter),
	)

	logger := zerolog.New(multiWriter).With().
		Timestamp().
		Logger()

	log.Logger = logger
}

func Initialize() {
	once.Do(initLogger)
	log.Info().Msg("日志模块已初始化")
}
